@writedocs/generator 0.10.14 → 0.10.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/astro.config.mjs +610 -572
  2. package/package.json +1 -1
  3. package/src/cli/generate-api-pages.js +418 -384
  4. package/src/cli/write-redirects-file.js +141 -116
  5. package/src/components/Accordion.astro +2 -1
  6. package/src/components/Callout.astro +1 -1
  7. package/src/components/CopyPageMenu.astro +1 -1
  8. package/src/components/Image.astro +19 -3
  9. package/src/components/Parameter.astro +11 -6
  10. package/src/components/Visibility.astro +11 -1
  11. package/src/layout/BaseLayout.astro +896 -831
  12. package/src/layout/components/AnalyticsScripts.astro +45 -77
  13. package/src/layout/components/Breadcrumbs.astro +1 -1
  14. package/src/layout/components/ConsentBanner.astro +118 -0
  15. package/src/layout/components/MobileMenu.astro +3 -2
  16. package/src/layout/components/Sidebar.astro +2 -2
  17. package/src/layout/components/SiteFooter.astro +3 -2
  18. package/src/layout/components/TopBar.astro +3 -2
  19. package/src/layout/styles/base.css +30 -0
  20. package/src/lib/agent-directive.js +47 -0
  21. package/src/lib/agent-markdown.js +22 -2
  22. package/src/lib/components-to-markdown.js +297 -0
  23. package/src/lib/config-schema.js +97 -10
  24. package/src/lib/config-schema.ts +1882 -1768
  25. package/src/lib/consent.js +102 -0
  26. package/src/lib/font-fallback.js +79 -0
  27. package/src/lib/image-size.js +140 -0
  28. package/src/lib/item-pages.js +63 -0
  29. package/src/lib/json-ld.js +127 -0
  30. package/src/lib/json-schema-descriptions.js +226 -212
  31. package/src/lib/last-modified.js +52 -0
  32. package/src/lib/link-check.js +506 -500
  33. package/src/lib/mcp-index.ts +1 -1
  34. package/src/lib/meta-description.js +41 -0
  35. package/src/lib/mintlify-convert.js +605 -603
  36. package/src/lib/moved-api-pages.js +54 -0
  37. package/src/lib/openapi-markdown.ts +16 -6
  38. package/src/lib/project-files-integration.js +61 -0
  39. package/src/lib/project-files.js +126 -0
  40. package/src/lib/rehype-image-loading.js +71 -0
  41. package/src/lib/robots-txt.js +16 -0
  42. package/src/lib/seo-tags.js +137 -0
  43. package/src/lib/styles-asset-integration.js +21 -3
  44. package/src/pages/[...slug].astro +22 -3
  45. package/src/pages/[...slug].md.ts +15 -5
  46. package/src/pages/llms-full.txt.ts +1 -1
  47. package/src/scripts/consent.ts +62 -0
  48. package/writedocs.schema.json +100 -0
package/astro.config.mjs CHANGED
@@ -1,572 +1,610 @@
1
- import { defineConfig } from 'astro/config';
2
- import mdx from '@astrojs/mdx';
3
- import react from '@astrojs/react';
4
- import icon from 'astro-icon';
5
- import sitemap from '@astrojs/sitemap';
6
- import tailwindcss from '@tailwindcss/vite';
7
- import path from 'node:path';
8
- import fs from 'node:fs';
9
- import { fileURLToPath } from 'node:url';
10
- import matter from 'gray-matter';
11
- import { unified } from '@astrojs/markdown-remark';
12
- import {
13
- transformerMetaHighlight,
14
- transformerMetaWordHighlight,
15
- transformerNotationHighlight,
16
- transformerNotationWordHighlight,
17
- transformerNotationFocus,
18
- transformerNotationDiff,
19
- transformerNotationErrorLevel,
20
- } from '@shikijs/transformers';
21
- import { codeBlockTransformer } from './src/lib/shiki-code-block.js';
22
- import { rehypeMermaid } from './src/lib/mermaid-rehype.js';
23
- import remarkMath from 'remark-math';
24
- import rehypeKatex from 'rehype-katex';
25
- import { remarkAutoHydrateSnippets } from './src/lib/mdx-auto-hydrate.js';
26
- import { remarkInjectBuiltinComponents } from './src/lib/mdx-inject-builtins.js';
27
- import { remarkTitleAnchorIds } from './src/lib/mdx-title-anchor-ids.js';
28
- import { remarkSubstituteVariables } from './src/lib/mdx-substitute-variables.js';
29
- import {
30
- remarkMintlifyTreeLists,
31
- remarkMintlifyPromptText,
32
- remarkMintlifyReactHooks,
33
- mintlifyReactHooksPlugin,
34
- } from './src/lib/mdx-mintlify.js';
35
- import { remarkUnknownComponentFallback } from './src/lib/mdx-unknown-components.js';
36
- import { remarkExtractInlineReactComponents } from './src/lib/mdx-inline-react.js';
37
- import { writedocsTempDir, writedocsBuildStagingDir } from './src/lib/writedocs-temp-dir.js';
38
- import { stylesAssetFallback } from './src/lib/styles-asset-integration.js';
39
- import { mcpDevServer } from './src/lib/mcp-dev-integration.js';
40
- import { configReload } from './src/lib/config-reload-integration.js';
41
- import { canonicalPath } from './src/lib/canonical-path.js';
42
- import { folderAddresses } from './src/lib/folder-redirects.js';
43
- import { report } from './src/lib/cli-report.js';
44
- import {
45
- loadDocsConfig,
46
- resolveCodeblockTheme,
47
- resolveCodeblockLangAlias,
48
- resolveSiteUrl,
49
- normalizeEntryId,
50
- findAllPages,
51
- } from './src/lib/config.ts';
52
-
53
- const contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd();
54
- // See writedocsBuildStagingDir()'s own comment (writedocs-temp-dir.js) for
55
- // why `outDir` below points here instead of directly at contentDir/dist -
56
- // short version: keeps Astro's own build executing inside the package (so
57
- // its dependencies' own module resolution keeps working), while build.js
58
- // does the actual cross-filesystem-safe copy into contentDir/dist as an
59
- // explicit final step once the build itself is done.
60
- const packageRoot = canonicalPath(process.env.WRITEDOCS_PACKAGE_ROOT || path.dirname(fileURLToPath(import.meta.url)));
61
- // Where this package's dependencies are: the node_modules folder that
62
- // contains an installed package (<project>/node_modules/@writedocs/
63
- // generator -> <project>/node_modules), or packageRoot itself in a checkout,
64
- // whose own node_modules is inside it. Used for the dev server's file-serving
65
- // allow list below.
66
- const nodeModulesAt = packageRoot.lastIndexOf(`${path.sep}node_modules${path.sep}`);
67
- const dependencyRoot = nodeModulesAt === -1 ? packageRoot : packageRoot.slice(0, nodeModulesAt + `${path.sep}node_modules`.length);
68
-
69
- // Read here (rather than deferred to page-render time, where
70
- // loadDocsConfig() is also called from [...slug].astro) specifically so
71
- // a site's writedocs.json can pick its own Shiki theme names - astro.config.mjs
72
- // is where Shiki itself actually gets configured, and dev.js/build.js
73
- // already guarantee writedocs.json exists and is valid JSON (preflightCheck())
74
- // before runAstro() ever gets this far, so letting loadDocsConfig() throw
75
- // its own validation error on a malformed writedocs.json here is consistent
76
- // with how every other consumer of it in this codebase behaves - no
77
- // special-casing needed.
78
- const docsConfig = loadDocsConfig(contentDir);
79
- // resolveCodeblockTheme() is the single source of truth for the
80
- // github-light/github-dark fallback - also used by ApiReferencePanel.astro
81
- // for its own separate <Code/> usages (which don't inherit
82
- // markdown.shikiConfig at all), so both stay in sync off the same
83
- // writedocs.json field.
84
- const codeblockTheme = resolveCodeblockTheme(docsConfig);
85
- // resolveCodeblockLangAlias() - see its own comment in lib/config.ts for
86
- // why this exists: some bundled Shiki grammars (mdx, notably) parse
87
- // without error but produce no real token differentiation under this
88
- // theme, so a ```lang fence renders as one flat color instead of
89
- // highlighted. Remaps a fence's language tag to a better-behaved grammar
90
- // before Shiki ever sees it - built-in mdx -> jsx default, plus whatever
91
- // a site adds of its own under writedocs.json's styles.codeblocks.langAlias.
92
- const codeblockLangAlias = resolveCodeblockLangAlias(docsConfig);
93
-
94
- // publicDir defaults relative to Astro's --root (always the writedocs
95
- // package itself - see src/cli/run-astro.js), not the content directory
96
- // being built. Point it at <contentDir>/public instead so a site's own
97
- // static assets (logos, favicons, ...) actually get copied/served -
98
- // falling back to Astro's normal default (<packageRoot>/public, which
99
- // doesn't exist in this package) when a site has no public/ of its own,
100
- // since passing a nonexistent publicDir is a hard Astro error.
101
- const contentPublicDir = path.join(contentDir, 'public');
102
-
103
- // Sitemap generation needs an absolute origin to build absolute <loc>
104
- // entries against - writedocs.json's `domain` field (see resolveSiteUrl() in
105
- // lib/config.ts) is the single source of truth for that, shared with the
106
- // canonical/OG/Twitter URL tags BaseLayout.astro renders per-page. A site
107
- // with no `domain` set (most fixtures, local-only builds) just doesn't
108
- // get a sitemap.xml at all - @astrojs/sitemap requires Astro's own `site`
109
- // config to be set and would otherwise throw, and a sitemap of
110
- // document-relative URLs isn't meaningful anyway.
111
- const siteUrl = resolveSiteUrl(docsConfig);
112
- if (!siteUrl) {
113
- report(
114
- 'info',
115
- 'No "domain" set in writedocs.json, so no sitemap.xml was generated, and llms.txt, the MCP server\'s page URLs and the "Open in…" links in the page menu use relative addresses or the address the page is opened from. Set "domain" to the site\'s address, like "docs.example.com".'
116
- );
117
- }
118
-
119
- /** Recursively lists every .md/.mdx file under `baseDir` (Node 20's
120
- * recursive readdir, no extra glob dependency needed - matches the
121
- * plain-fs-walk style already used by generate-api-pages.js's
122
- * findHandWrittenOverrides()), or an empty list if the directory doesn't
123
- * exist (e.g. a site with no OpenAPI groups has no generated-docs/ at
124
- * all under writedocsTempDir()). */
125
- function walkMdFiles(baseDir) {
126
- if (!fs.existsSync(baseDir)) return [];
127
- return fs
128
- .readdirSync(baseDir, { recursive: true })
129
- .filter((f) => /\.mdx?$/i.test(f))
130
- .map((f) => path.join(baseDir, f));
131
- }
132
-
133
- /** The set of normalized page ids (see normalizeEntryId()) whose
134
- * frontmatter sets `seo.noindex: true` - excluded from sitemap.xml below,
135
- * since listing a page there while also telling crawlers not to index it
136
- * (BaseLayout.astro's <meta name="robots" content="noindex..."> for the
137
- * same flag) would be self-contradictory. Reads frontmatter directly via
138
- * gray-matter rather than astro:content, which doesn't exist yet this
139
- * early in Astro's own startup - the same reason
140
- * generate-api-pages.js's own frontmatter scanning does the same thing.
141
- *
142
- * Reuses findAllPages() from lib/config.ts (rather than its own
143
- * hand-rolled walk) for the hand-written-page half of this scan, so it
144
- * always sees exactly the same file set that actually becomes a page in
145
- * the `pages` collection - no risk of the two independently drifting
146
- * apart on which directories get excluded. The fallback id
147
- * (`relativeId` with its extension and any trailing `/index` segment
148
- * stripped) mirrors fileIdForEntry()'s own algorithm in lib/config.ts,
149
- * for a page with no explicit `slug` override. */
150
- function collectNoindexIds(rootContentDir) {
151
- const generatedDocsDir = path.join(writedocsTempDir(rootContentDir), 'generated-docs');
152
- const ids = new Set();
153
- // Whether some page is served at "/" itself. When none is, "/" is the
154
- // redirect-only route [...slug].astro synthesizes (noindex, pointing at
155
- // the first page) - which doesn't belong in the sitemap either.
156
- let rootIsPage = false;
157
- const pageIds = [];
158
-
159
- for (const relativeId of findAllPages(rootContentDir)) {
160
- const file = path.join(rootContentDir, relativeId);
161
- const { data } = matter(fs.readFileSync(file, 'utf-8'));
162
- const pageId = normalizeEntryId(data?.slug ?? relativeId.replace(/\.mdx?$/i, '').replace(/\/index$/, ''));
163
- if (pageId === 'index') rootIsPage = true;
164
- pageIds.push(pageId);
165
- // Top-level `noindex` is Mintlify's spelling, and a Mintlify `hidden`
166
- // page is noindexed too - content.config.ts folds both into
167
- // `seo.noindex` the same way (an explicit value wins).
168
- // A frontmatter `url` page's route only redirects to that link, so it
169
- // doesn't belong in the sitemap either.
170
- if (!(data?.seo?.noindex ?? data?.noindex ?? data?.hidden === true) && !data?.url) continue;
171
- ids.add(pageId);
172
- }
173
- // Generated OpenAPI stub pages always set an explicit `slug` (see
174
- // generate-api-pages.js) - there's no file-path-derived id to fall back
175
- // to the way there is for a hand-written page.
176
- for (const file of walkMdFiles(generatedDocsDir)) {
177
- const { data } = matter(fs.readFileSync(file, 'utf-8'));
178
- if (data?.slug && normalizeEntryId(data.slug) === 'index') rootIsPage = true;
179
- if (data?.slug) pageIds.push(normalizeEntryId(data.slug));
180
- if ((data?.seo?.noindex ?? data?.noindex ?? data?.hidden === true) && data.slug) ids.add(normalizeEntryId(data.slug));
181
- }
182
- if (!rootIsPage) ids.add('index');
183
- // Folder addresses with no page of their own redirect to one under them
184
- // (lib/folder-redirects.js) - redirects, so not in the sitemap either.
185
- for (const folder of folderAddresses(pageIds)) ids.add(folder);
186
- return ids;
187
- }
188
-
189
- const noindexIds = siteUrl ? collectNoindexIds(contentDir) : new Set();
190
-
191
- /** O @astrojs/sitemap sempre grava um sitemap-index.xml apontando para
192
- * sitemap-0.xml, sitemap-1.xml, ... - mesmo quando há um arquivo só, que é
193
- * o caso de todo site de docs abaixo de 50.000 páginas. Aqui o único
194
- * sitemap-0.xml vira sitemap.xml (o endereço que crawler e ferramenta de
195
- * SEO procuram primeiro) e o índice é apagado. Com mais de um arquivo o
196
- * índice é necessário (o protocolo não permite um único arquivo acima de
197
- * 50.000 URLs), então tudo fica como o plugin gravou. Um sitemap.xml
198
- * vindo do public/ do próprio site também não é sobrescrito. */
199
- function singleSitemapFile() {
200
- return {
201
- name: 'writedocs-single-sitemap',
202
- hooks: {
203
- 'astro:build:done': ({ dir }) => {
204
- const outDir = fileURLToPath(dir);
205
- const chunks = fs.readdirSync(outDir).filter((f) => /^sitemap-\d+\.xml$/.test(f));
206
- const target = path.join(outDir, 'sitemap.xml');
207
- if (chunks.length !== 1) {
208
- report('debug', `${chunks.length} sitemap files generated - keeping sitemap-index.xml.`);
209
- return;
210
- }
211
- if (fs.existsSync(target)) {
212
- report('info', 'public/sitemap.xml exists, so it was kept - the generated sitemap is sitemap-index.xml.');
213
- return;
214
- }
215
- fs.renameSync(path.join(outDir, chunks[0]), target);
216
- fs.rmSync(path.join(outDir, 'sitemap-index.xml'), { force: true });
217
- // O próprio plugin acabou de logar "sitemap-index.xml created"; esta
218
- // linha diz o que de fato ficou no build.
219
- report('debug', `Replaced ${chunks[0]} + sitemap-index.xml with a single sitemap.xml.`);
220
- },
221
- },
222
- };
223
- }
224
-
225
- // writedocs.json's `redirects` array -> Astro's own `redirects` config option
226
- // (a plain `{ [source]: destination }` record - see redirectSchema in
227
- // lib/config.ts for why there's no `permanent`/status-code field: this
228
- // package always builds `output: 'static'` with no adapter installed, and
229
- // Astro's own docs say a static redirect is always a client-side
230
- // `<meta http-equiv="refresh">` page regardless of what status is asked
231
- // for). Omitted entirely (rather than passed as `{}`) when a site has no
232
- // redirects configured, matching the `siteUrl ? [...] : []` pattern above
233
- // of only opting into a feature's config surface when it's actually used.
234
- const redirectsConfig = Object.fromEntries(docsConfig.redirects.map((r) => [r.source, r.destination]));
235
-
236
- /** Tailwind only scans the Vite root for class names - this package, not
237
- * the site being built, which is usually somewhere else entirely - so a
238
- * utility class written in a site's own MDX or snippet (Mintlify content
239
- * uses them freely, e.g. className="block dark:hidden") never got
240
- * generated. Appends an @source for the site's content files to
241
- * global.css before Tailwind compiles it. Forward slashes, since
242
- * Tailwind reads the path as a glob. */
243
- function contentTailwindSource() {
244
- const sourceGlob = `${contentDir.split(path.sep).join('/')}/**/*.{md,mdx,jsx,tsx}`;
245
- return {
246
- name: 'writedocs:content-tailwind-source',
247
- enforce: 'pre',
248
- transform(code, id) {
249
- if (!id.split('?')[0].replace(/\\/g, '/').endsWith('/src/styles/global.css')) return null;
250
- return { code: `${code}\n@source ${JSON.stringify(sourceGlob)};\n`, map: null };
251
- },
252
- };
253
- }
254
-
255
- export default defineConfig({
256
- ...(siteUrl ? { site: siteUrl } : {}),
257
- ...(docsConfig.redirects.length ? { redirects: redirectsConfig } : {}),
258
- // Astro's own dev-mode toolbar (the floating pill in the bottom center
259
- // of every page - inspect/audit/settings) is a tool for authoring
260
- // Astro itself, not something a writedocs site's own reader/author
261
- // should see while running `writedocs dev` - it's not exposed as a
262
- // writedocs.json option (nothing site-specific to configure here) since
263
- // there's no scenario where a writedocs project actually wants it on.
264
- // Off in every environment (build never shows it anyway, since it's a
265
- // dev-only overlay Astro strips from production output regardless).
266
- devToolbar: { enabled: false },
267
- // Not contentDir/dist directly - see writedocsBuildStagingDir()'s own
268
- // comment (writedocs-temp-dir.js) for why, and build.js for the copy
269
- // step that actually gets a finished build from here into the real
270
- // <contentDir>/dist a reader/host ever sees. Irrelevant to `astro dev`
271
- // (no build output involved), so this applies unconditionally rather
272
- // than branching on which CLI command is running.
273
- outDir: writedocsBuildStagingDir(packageRoot, contentDir),
274
- cacheDir: path.join(writedocsTempDir(contentDir), 'cache'),
275
- ...(fs.existsSync(contentPublicDir) ? { publicDir: contentPublicDir } : {}),
276
- // icon() reads from whatever @iconify-json/* collections are installed
277
- // (see package.json) and inlines only the specific icons a build
278
- // actually references as <svg> - the installed collections don't
279
- // affect output size beyond that. No `include` config needed: astro-icon
280
- // resolves "collection:icon-name" against any installed collection
281
- // automatically.
282
- integrations: [
283
- // markdown.processor (below) carries remarkAutoHydrateSnippets - see
284
- // its own comment there for why it's attached there and not here.
285
- // Auto-adds `client:load` to every usage of a component imported from
286
- // a .jsx/.tsx file (a snippet - see docs/dev/docs/snippets.mdx) that
287
- // doesn't already carry its own `client:*` attribute, so a snippet
288
- // just works when dropped into a page - nobody using it needs to know
289
- // Astro's hydration-directive syntax exists at all, only someone who
290
- // wants a *different* strategy (client:visible/idle/only) needs to
291
- // write one explicitly.
292
- mdx(),
293
- // Lets a site's own snippets (see docs/dev/docs/snippets.mdx) be real
294
- // .jsx/.tsx React components - hooks and all - dropped straight into
295
- // MDX and hydrated client-side as an Astro island (automatically -
296
- // see remarkAutoHydrateSnippets above). writedocs' own built-in
297
- // components (Callout, Card, ...) stay plain .astro files - this is
298
- // purely for snippets a site author writes themselves.
299
- react(),
300
- icon(),
301
- ...(siteUrl
302
- ? [
303
- sitemap({
304
- // Teto do protocolo de sitemap por arquivo (o default do
305
- // @astrojs/sitemap é 45.000). Até aqui, tudo cabe num único
306
- // sitemap.xml - ver singleSitemapFile() abaixo.
307
- entryLimit: 50000,
308
- filter: (page) => {
309
- const pathname = new URL(page).pathname;
310
- const id = normalizeEntryId(pathname);
311
- return !noindexIds.has(id);
312
- },
313
- }),
314
- // Precisa vir depois do sitemap(): o Astro roda os hooks
315
- // astro:build:done na ordem deste array, um de cada vez.
316
- singleSitemapFile(),
317
- ]
318
- : []),
319
- // Lets styles.favicon/styles.logo/styles.background.images/seo.ogImage/
320
- // styles.fonts.*.source resolve from anywhere in the project, not just
321
- // public/ - see collectConfiguredAssetPaths() (lib/config.ts) for the
322
- // field list and styles-asset-integration.js for how it's actually
323
- // served/copied.
324
- stylesAssetFallback(contentDir),
325
- // /mcp in `writedocs dev`, as the build's dist/_worker.js serves it -
326
- // see src/lib/mcp-dev-integration.js.
327
- mcpDevServer({ version: JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf-8')).version }),
328
- // writedocs dev: an edit to writedocs.json reloads the open tab.
329
- configReload({ configPath: path.join(contentDir, 'writedocs.json') }),
330
- ],
331
- output: 'static',
332
- // Dual Shiki themes for fenced code blocks (```) in MDX content, so
333
- // they switch with the site's own [data-theme] toggle instead of
334
- // always rendering Astro's single default (github-dark) regardless of
335
- // light/dark mode. Defaults to github-light/github-dark, overridable
336
- // per-site via writedocs.json's styles.codeblocks.{light,dark} (any Shiki
337
- // theme *name* - see https://shiki.style/themes for the built-in
338
- // list - not a custom theme object/JSON file, at least for now).
339
- // Astro bakes the "light" theme's colors as the element's base inline
340
- // style and adds --shiki-dark/--shiki-dark-bg (etc.) custom
341
- // properties alongside it - see the
342
- // [data-theme='dark'] :global(.astro-code) override in
343
- // BaseLayout.astro that actually swaps to them.
344
- markdown: {
345
- // Excludes ```mermaid fences from Shiki's own tokenization entirely -
346
- // they reach rehypeMermaid (below) as plain, un-highlighted text,
347
- // which is what mermaid.js needs to parse and render them into an
348
- // actual diagram client-side (see [...slug].astro's initMermaid()).
349
- // Syntax-highlighting mermaid's own pseudo-language as if it were
350
- // source code would be actively wrong here - the goal is a rendered
351
- // diagram, not colored diagram-description text.
352
- syntaxHighlight: { type: 'shiki', excludeLangs: ['mermaid'] },
353
- // Astro 7's markdown.rehypePlugins (top-level) is deprecated in favor
354
- // of passing plugins straight to the `unified` processor itself -
355
- // functionally identical (Astro's own deprecated-option shim used to
356
- // just forward the top-level array into this exact processor), just
357
- // explicit instead of relying on that shim (and the console warning
358
- // it prints on every build/dev run). Astro still runs this *after*
359
- // its own internal Shiki step (see @astrojs/markdown-remark's
360
- // index.js) regardless of which processor plugins are attached to,
361
- // so rehypeMermaid still always sees the excluded ```mermaid block
362
- // completely untouched by Shiki - exactly the plain
363
- // <pre><code class="language-mermaid"> shape it expects to reshape
364
- // into mermaid.js's <div class="mermaid"> form.
365
- // remarkInjectBuiltinComponents/remarkAutoHydrateSnippets only ever
366
- // match JSX/import nodes that exist solely in MDX's extended syntax
367
- // tree (see mdx-inject-builtins.js/mdx-auto-hydrate.js) - running them
368
- // here rather than passing them to mdx({ remarkPlugins }) avoids that
369
- // option's own deprecation warning ("pass it to unified()... MDX will
370
- // inherit it" - extendMarkdownConfig defaults to true, so mdx() below
371
- // already picks this processor up automatically). Harmless no-op on
372
- // plain .md content, which never has an mdxjsEsm/mdxJsxFlowElement
373
- // node to match in the first place.
374
- // remarkSubstituteVariables is a parameterized plugin (an "attacher"
375
- // that takes writedocs.json's `variables` map as its options and returns
376
- // the actual transformer) - passed as a unified [attacher, options]
377
- // tuple, *not* pre-called (`remarkSubstituteVariables(docsConfig.variables)`
378
- // directly in this array). unified's own `use()` always calls
379
- // whatever it finds in this array as if it were the attacher itself;
380
- // handing it an already-produced transformer function makes unified
381
- // invoke *that* with zero arguments during its `freeze()` setup pass,
382
- // which crashes deep inside unist-util-visit ("Cannot use 'in'
383
- // operator to search for 'children' in undefined") the first time any
384
- // MDX page actually builds - a real bug hit and fixed while testing
385
- // 25-site-config, not a hypothetical. remarkInjectBuiltinComponents/
386
- // remarkAutoHydrateSnippets don't need this tuple form since neither
387
- // takes options - they're valid attachers as bare function references.
388
- // A site with no `variables` set still gets this plugin instance
389
- // (which then no-ops on every file - see its own early-return) rather
390
- // than being conditionally omitted, keeping this array's shape static
391
- // regardless of writedocs.json content.
392
- processor: unified({
393
- // remarkMath goes first: it parses $inline$ and standalone $$block$$
394
- // math into their own `inlineMath`/`math` mdast node types (mdast-
395
- // util-to-hast has built-in support for both, turning them into a
396
- // <span>/<div> carrying the raw LaTeX source as a "language-math"
397
- // code-like payload for rehypeKatex, below, to render). Running it
398
- // before remarkSubstituteVariables means a $...$ span's raw LaTeX
399
- // source is no longer a plain `text` node by the time that plugin's
400
- // visitor runs (it only visits `text` nodes - see its own comment) -
401
- // not that `[[key]]` syntax inside actual LaTeX is a realistic thing
402
- // to write, but this keeps the two plugins' node-type boundaries
403
- // clean rather than leaving it to chance which one sees a math span
404
- // as raw text first.
405
- remarkPlugins: [
406
- remarkMath,
407
- // Mintlify's Markdown-list <Tree> and <Prompt> source text - see
408
- // lib/mdx-mintlify.js. Before remarkInjectBuiltinComponents, so
409
- // the <Tree.Folder>/<Tree.File> elements they add are already in
410
- // the tree when it looks for components to import.
411
- remarkMintlifyTreeLists,
412
- remarkMintlifyPromptText,
413
- // An inline component that calls React hooks moves into a generated
414
- // .jsx file so it runs as real React (and hydrates) - see
415
- // lib/mdx-inline-react.js. Before remarkMintlifyReactHooks, which
416
- // imports any hooks the page itself still calls (Mintlify
417
- // pre-injects them), and before remarkAutoHydrateSnippets, which
418
- // hydrates the component through its new .jsx import.
419
- remarkExtractInlineReactComponents,
420
- remarkMintlifyReactHooks,
421
- // An unknown component becomes a fragment (its children still
422
- // render) with a warning, instead of failing the whole build - see
423
- // lib/mdx-unknown-components.js. After remarkMintlifyTreeLists, so
424
- // the <Tree.Folder>/<Tree.File> elements it adds count as known.
425
- remarkUnknownComponentFallback,
426
- remarkInjectBuiltinComponents,
427
- // Runs after remarkInjectBuiltinComponents (order doesn't actually
428
- // matter between them - that plugin only ever prepends an import
429
- // statement, never touches an existing JSX node's attributes) but
430
- // grouped right next to it since both deal with the same set of
431
- // built-in component tag names. See its own comment for why this
432
- // has to be a whole-document pass rather than logic living inside
433
- // Callout.astro/Accordion.astro themselves.
434
- remarkTitleAnchorIds,
435
- remarkAutoHydrateSnippets,
436
- [remarkSubstituteVariables, docsConfig.variables],
437
- ],
438
- // rehypeKatex renders every math/inlineMath node remarkMath produced
439
- // into real KaTeX markup (a <span class="katex">...</span> tree of
440
- // MathML + HTML, not an image or client-rendered widget) - fully at
441
- // build time, so unlike Mermaid there's no client-side JS or runtime
442
- // cost at all, just the one katex.min.css import (BaseLayout.astro)
443
- // for layout/glyph styling. Order relative to rehypeMermaid doesn't
444
- // matter - they walk disjoint hast node shapes (pre>code.language-
445
- // mermaid vs. remarkMath's own math/inlineMath-derived nodes) and
446
- // neither plugin's output is visible to the other.
447
- rehypePlugins: [rehypeMermaid, rehypeKatex],
448
- }),
449
- shikiConfig: {
450
- themes: codeblockTheme,
451
- langAlias: codeblockLangAlias,
452
- // The official @shikijs/transformers annotation transformers -
453
- // enabled sitewide so any fenced code block can use their meta-
454
- // string/comment syntax without per-page opt-in:
455
- // ```js {1,3-5} -> transformerMetaHighlight
456
- // ```js /someWord/ -> transformerMetaWordHighlight
457
- // // [!code highlight] -> transformerNotationHighlight
458
- // // [!code word:someWord] -> transformerNotationWordHighlight
459
- // // [!code focus] -> transformerNotationFocus
460
- // // [!code ++] / // [!code --] -> transformerNotationDiff
461
- // // [!code error] / [!code warning] -> transformerNotationErrorLevel
462
- // (comment syntax adapts to the language - # for Python/bash, //
463
- // for JS/etc - see each transformer's own docs at shiki.style).
464
- // Plus codeBlockTransformer, writedocs' own transformer for the
465
- // copy button, an optional title bar, and wrap/lines/expandable
466
- // meta flags - see src/lib/shiki-code-block.js. It runs last so
467
- // its `root` hook wraps the <pre> only after every class the
468
- // transformers above added to it is already in place - though in
469
- // practice this doesn't matter, since all `pre`/`line` hooks
470
- // across every transformer run to completion before any `root`
471
- // hook runs at all (two separate passes, not interleaved).
472
- transformers: [
473
- transformerMetaHighlight(),
474
- transformerMetaWordHighlight(),
475
- transformerNotationHighlight(),
476
- transformerNotationWordHighlight(),
477
- transformerNotationFocus(),
478
- transformerNotationDiff(),
479
- transformerNotationErrorLevel(),
480
- codeBlockTransformer(),
481
- ],
482
- },
483
- },
484
- // Tailwind is available for future/custom content (e.g. hand-authored
485
- // MDX) but nothing in writedocs' own components has been migrated to
486
- // it - they still use scoped <style> blocks + the --wd-* CSS variables
487
- // so per-site writedocs.json theming (colors, and now dark mode) keeps
488
- // working. See src/styles/global.css for the one @import that wires
489
- // Tailwind's utilities in.
490
- vite: {
491
- // The dev server only serves files under its workspace root by default.
492
- // A site's own snippets live in its content directory, and inline React
493
- // components moved out of pages (lib/mdx-inline-react.js) in writedocs'
494
- // temp directory - both need to reach the browser to hydrate. Setting
495
- // `allow` replaces Vite's default rather than adding to it, so the
496
- // package's dependencies must stay reachable too: when writedocs is
497
- // installed, they sit next to it in the node_modules folder that
498
- // contains it (React's own hydration client included), not inside
499
- // packageRoot - see dependencyRoot above.
500
- server: {
501
- fs: {
502
- allow: [packageRoot, dependencyRoot, contentDir, writedocsTempDir(contentDir)],
503
- },
504
- },
505
- // contentTailwindSource() must come before tailwindcss(): both are
506
- // enforce: 'pre' transforms, which Vite runs in array order, and
507
- // Tailwind has to see the added @source when it compiles global.css.
508
- // mintlifyReactHooksPlugin() does for a site's .jsx/.tsx snippets what
509
- // remarkMintlifyReactHooks does for its MDX pages.
510
- plugins: [contentTailwindSource(), tailwindcss(), mintlifyReactHooksPlugin(contentDir)],
511
- // `writedocs dev`: Vite only prepares for the browser the dependencies
512
- // it finds by scanning the project's own source - and when writedocs is
513
- // installed, its source sits in node_modules, which the scan skips. The
514
- // page script's `import("mermaid")` ([...slug].astro) was then served
515
- // as it is, and its CommonJS dependencies failed in the browser ("dayjs
516
- // ... does not provide an export named 'default'"): diagrams stayed as
517
- // text in dev, while builds were fine. Naming it here prepares it always.
518
- optimizeDeps: {
519
- include: ['mermaid'],
520
- },
521
- resolve: {
522
- alias: [
523
- // Lets a page's MDX write `import Foo from '/snippets/foo.mdx'`
524
- // (Mintlify's own snippet-import convention) instead of a
525
- // relative path whose "../" depth depends on how deeply nested
526
- // the importing page happens to be - see docs/dev/docs/snippets.mdx
527
- // for the full feature writeup. Vite's project root is always
528
- // packageRoot (this package itself - see run-astro.js), not
529
- // contentDir, so a real leading-slash import would otherwise
530
- // resolve (and fail to find anything) inside this package
531
- // instead of the site's own content directory; this alias
532
- // redirects just that one prefix to contentDir/snippets/ instead.
533
- { find: /^\/snippets\//, replacement: path.join(contentDir, 'snippets') + '/' },
534
- // remarkInjectBuiltinComponents (mdx-inject-builtins.js) auto-
535
- // injects `import { Callout, ... } from 'writedocs/components'`
536
- // into any .mdx file that uses a built-in component tag without
537
- // importing it itself - a real bare specifier Vite has to resolve
538
- // as if the .mdx file had written it. package.json's own
539
- // `exports: { "./components": "./src/components/index.ts" }`
540
- // makes that specifier valid *in principle* (Node's package
541
- // self-reference feature - a package importing its own name), but
542
- // self-reference only resolves when the importing file is a
543
- // descendant of this package's own package.json - true for every
544
- // existing fixture (always built from inside this repo/package
545
- // tree) but never true for a real consumer's content, which lives
546
- // in a completely separate directory in the actual product
547
- // architecture (see docs/dev/docs/architecture.mdx) - walking up
548
- // from such a file never finds a package.json named "writedocs",
549
- // so self-reference fails and Vite reports the bare specifier as
550
- // unresolvable ("Rolldown failed to resolve import
551
- // 'writedocs/components'").
552
- // This alias bypasses self-reference resolution entirely for
553
- // that one specifier - Vite's alias matching is a plain string
554
- // match against the specifier itself, independent of which file
555
- // imported it, so it resolves correctly regardless of where the
556
- // content directory actually lives. WRITEDOCS_PACKAGE_ROOT is the
557
- // same packageRoot value already set by run-astro.js for
558
- // lib/config.ts's fileIdForEntry() to consume - reusing it here
559
- // instead of recomputing via import.meta.url keeps there being
560
- // exactly one source of truth for "where this package lives" per
561
- // astro subprocess. Falls back to this file's own directory
562
- // (astro.config.mjs always lives at packageRoot) for anything
563
- // that ever imports this config outside that subprocess, e.g. a
564
- // future test harness.
565
- {
566
- find: 'writedocs/components',
567
- replacement: path.join(packageRoot, 'src/components/index.ts'),
568
- },
569
- ],
570
- },
571
- },
572
- });
1
+ import { defineConfig } from 'astro/config';
2
+ import mdx from '@astrojs/mdx';
3
+ import react from '@astrojs/react';
4
+ import icon from 'astro-icon';
5
+ import sitemap from '@astrojs/sitemap';
6
+ import tailwindcss from '@tailwindcss/vite';
7
+ import path from 'node:path';
8
+ import fs from 'node:fs';
9
+ import { fileURLToPath } from 'node:url';
10
+ import matter from 'gray-matter';
11
+ import { unified } from '@astrojs/markdown-remark';
12
+ import {
13
+ transformerMetaHighlight,
14
+ transformerMetaWordHighlight,
15
+ transformerNotationHighlight,
16
+ transformerNotationWordHighlight,
17
+ transformerNotationFocus,
18
+ transformerNotationDiff,
19
+ transformerNotationErrorLevel,
20
+ } from '@shikijs/transformers';
21
+ import { codeBlockTransformer } from './src/lib/shiki-code-block.js';
22
+ import { rehypeMermaid } from './src/lib/mermaid-rehype.js';
23
+ import remarkMath from 'remark-math';
24
+ import rehypeKatex from 'rehype-katex';
25
+ import { remarkAutoHydrateSnippets } from './src/lib/mdx-auto-hydrate.js';
26
+ import { remarkInjectBuiltinComponents } from './src/lib/mdx-inject-builtins.js';
27
+ import { remarkTitleAnchorIds } from './src/lib/mdx-title-anchor-ids.js';
28
+ import { remarkSubstituteVariables } from './src/lib/mdx-substitute-variables.js';
29
+ import {
30
+ remarkMintlifyTreeLists,
31
+ remarkMintlifyPromptText,
32
+ remarkMintlifyReactHooks,
33
+ mintlifyReactHooksPlugin,
34
+ } from './src/lib/mdx-mintlify.js';
35
+ import { remarkUnknownComponentFallback } from './src/lib/mdx-unknown-components.js';
36
+ import { remarkExtractInlineReactComponents } from './src/lib/mdx-inline-react.js';
37
+ import { writedocsTempDir, writedocsBuildStagingDir } from './src/lib/writedocs-temp-dir.js';
38
+ import { stylesAssetFallback } from './src/lib/styles-asset-integration.js';
39
+ import { mcpDevServer } from './src/lib/mcp-dev-integration.js';
40
+ import { configReload } from './src/lib/config-reload-integration.js';
41
+ import { canonicalPath } from './src/lib/canonical-path.js';
42
+ import { folderAddresses } from './src/lib/folder-redirects.js';
43
+ import { report } from './src/lib/cli-report.js';
44
+ import { publishProjectFiles, generatedRobotsTxt } from './src/lib/project-files-integration.js';
45
+ import { frontmatterNoindex, canonicalIsElsewhere } from './src/lib/seo-tags.js';
46
+ import { readMovedApiPages } from './src/lib/moved-api-pages.js';
47
+ import { rehypeImageLoading } from './src/lib/rehype-image-loading.js';
48
+ import { gitLastModified, newestDate } from './src/lib/last-modified.js';
49
+ import { readSpecPaths } from './src/lib/project-files.js';
50
+ import {
51
+ loadDocsConfig,
52
+ resolveCodeblockTheme,
53
+ resolveCodeblockLangAlias,
54
+ resolveSiteUrl,
55
+ normalizeEntryId,
56
+ findAllPages,
57
+ } from './src/lib/config.ts';
58
+
59
+ const contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd();
60
+ // See writedocsBuildStagingDir()'s own comment (writedocs-temp-dir.js) for
61
+ // why `outDir` below points here instead of directly at contentDir/dist -
62
+ // short version: keeps Astro's own build executing inside the package (so
63
+ // its dependencies' own module resolution keeps working), while build.js
64
+ // does the actual cross-filesystem-safe copy into contentDir/dist as an
65
+ // explicit final step once the build itself is done.
66
+ const packageRoot = canonicalPath(process.env.WRITEDOCS_PACKAGE_ROOT || path.dirname(fileURLToPath(import.meta.url)));
67
+ // Where this package's dependencies are: the node_modules folder that
68
+ // contains an installed package (<project>/node_modules/@writedocs/
69
+ // generator -> <project>/node_modules), or packageRoot itself in a checkout,
70
+ // whose own node_modules is inside it. Used for the dev server's file-serving
71
+ // allow list below.
72
+ const nodeModulesAt = packageRoot.lastIndexOf(`${path.sep}node_modules${path.sep}`);
73
+ const dependencyRoot = nodeModulesAt === -1 ? packageRoot : packageRoot.slice(0, nodeModulesAt + `${path.sep}node_modules`.length);
74
+
75
+ // Read here (rather than deferred to page-render time, where
76
+ // loadDocsConfig() is also called from [...slug].astro) specifically so
77
+ // a site's writedocs.json can pick its own Shiki theme names - astro.config.mjs
78
+ // is where Shiki itself actually gets configured, and dev.js/build.js
79
+ // already guarantee writedocs.json exists and is valid JSON (preflightCheck())
80
+ // before runAstro() ever gets this far, so letting loadDocsConfig() throw
81
+ // its own validation error on a malformed writedocs.json here is consistent
82
+ // with how every other consumer of it in this codebase behaves - no
83
+ // special-casing needed.
84
+ const docsConfig = loadDocsConfig(contentDir);
85
+ // resolveCodeblockTheme() is the single source of truth for the
86
+ // github-light/github-dark fallback - also used by ApiReferencePanel.astro
87
+ // for its own separate <Code/> usages (which don't inherit
88
+ // markdown.shikiConfig at all), so both stay in sync off the same
89
+ // writedocs.json field.
90
+ const codeblockTheme = resolveCodeblockTheme(docsConfig);
91
+ // resolveCodeblockLangAlias() - see its own comment in lib/config.ts for
92
+ // why this exists: some bundled Shiki grammars (mdx, notably) parse
93
+ // without error but produce no real token differentiation under this
94
+ // theme, so a ```lang fence renders as one flat color instead of
95
+ // highlighted. Remaps a fence's language tag to a better-behaved grammar
96
+ // before Shiki ever sees it - built-in mdx -> jsx default, plus whatever
97
+ // a site adds of its own under writedocs.json's styles.codeblocks.langAlias.
98
+ const codeblockLangAlias = resolveCodeblockLangAlias(docsConfig);
99
+
100
+ // publicDir defaults relative to Astro's --root (always the writedocs
101
+ // package itself - see src/cli/run-astro.js), not the content directory
102
+ // being built. Point it at <contentDir>/public instead so a site's own
103
+ // static assets (logos, favicons, ...) actually get copied/served -
104
+ // falling back to Astro's normal default (<packageRoot>/public, which
105
+ // doesn't exist in this package) when a site has no public/ of its own,
106
+ // since passing a nonexistent publicDir is a hard Astro error.
107
+ const contentPublicDir = path.join(contentDir, 'public');
108
+
109
+ // Sitemap generation needs an absolute origin to build absolute <loc>
110
+ // entries against - writedocs.json's `domain` field (see resolveSiteUrl() in
111
+ // lib/config.ts) is the single source of truth for that, shared with the
112
+ // canonical/OG/Twitter URL tags BaseLayout.astro renders per-page. A site
113
+ // with no `domain` set (most fixtures, local-only builds) just doesn't
114
+ // get a sitemap.xml at all - @astrojs/sitemap requires Astro's own `site`
115
+ // config to be set and would otherwise throw, and a sitemap of
116
+ // document-relative URLs isn't meaningful anyway.
117
+ const siteUrl = resolveSiteUrl(docsConfig);
118
+ if (!siteUrl) {
119
+ report(
120
+ 'info',
121
+ 'No "domain" set in writedocs.json, so no sitemap.xml was generated, and llms.txt, the MCP server\'s page URLs and the "Open in…" links in the page menu use relative addresses or the address the page is opened from. Set "domain" to the site\'s address, like "docs.example.com".'
122
+ );
123
+ }
124
+
125
+ /** Recursively lists every .md/.mdx file under `baseDir` (Node 20's
126
+ * recursive readdir, no extra glob dependency needed - matches the
127
+ * plain-fs-walk style already used by generate-api-pages.js's
128
+ * findHandWrittenOverrides()), or an empty list if the directory doesn't
129
+ * exist (e.g. a site with no OpenAPI groups has no generated-docs/ at
130
+ * all under writedocsTempDir()). */
131
+ function walkMdFiles(baseDir) {
132
+ if (!fs.existsSync(baseDir)) return [];
133
+ return fs
134
+ .readdirSync(baseDir, { recursive: true })
135
+ .filter((f) => /\.mdx?$/i.test(f))
136
+ .map((f) => path.join(baseDir, f));
137
+ }
138
+
139
+ /** The set of normalized page ids (see normalizeEntryId()) whose
140
+ * frontmatter sets `seo.noindex: true` - excluded from sitemap.xml below,
141
+ * since listing a page there while also telling crawlers not to index it
142
+ * (BaseLayout.astro's <meta name="robots" content="noindex..."> for the
143
+ * same flag) would be self-contradictory. Reads frontmatter directly via
144
+ * gray-matter rather than astro:content, which doesn't exist yet this
145
+ * early in Astro's own startup - the same reason
146
+ * generate-api-pages.js's own frontmatter scanning does the same thing.
147
+ *
148
+ * Reuses findAllPages() from lib/config.ts (rather than its own
149
+ * hand-rolled walk) for the hand-written-page half of this scan, so it
150
+ * always sees exactly the same file set that actually becomes a page in
151
+ * the `pages` collection - no risk of the two independently drifting
152
+ * apart on which directories get excluded. The fallback id
153
+ * (`relativeId` with its extension and any trailing `/index` segment
154
+ * stripped) mirrors fileIdForEntry()'s own algorithm in lib/config.ts,
155
+ * for a page with no explicit `slug` override. */
156
+ function collectNoindexIds(rootContentDir) {
157
+ const generatedDocsDir = path.join(writedocsTempDir(rootContentDir), 'generated-docs');
158
+ const ids = new Set();
159
+ // Whether some page is served at "/" itself. When none is, "/" is the
160
+ // redirect-only route [...slug].astro synthesizes (noindex, pointing at
161
+ // the first page) - which doesn't belong in the sitemap either.
162
+ let rootIsPage = false;
163
+ const pageIds = [];
164
+ // When each page last changed, for <lastmod> - see lib/last-modified.js.
165
+ const fileDates = gitLastModified(rootContentDir);
166
+
167
+ for (const relativeId of findAllPages(rootContentDir)) {
168
+ const file = path.join(rootContentDir, relativeId);
169
+ const { data } = matter(fs.readFileSync(file, 'utf-8'));
170
+ const pageId = normalizeEntryId(data?.slug ?? relativeId.replace(/\.mdx?$/i, '').replace(/\/index$/, ''));
171
+ if (pageId === 'index') rootIsPage = true;
172
+ pageIds.push(pageId);
173
+ const changed = fileDates?.get(relativeId.split(path.sep).join('/'));
174
+ if (changed) lastModifiedById.set(pageId, changed);
175
+ // Top-level `noindex` is Mintlify's spelling, and a Mintlify `hidden`
176
+ // page is noindexed too - content.config.ts folds both into
177
+ // `seo.noindex` the same way (an explicit value wins).
178
+ // A frontmatter `url` page's route only redirects to that link, so it
179
+ // doesn't belong in the sitemap either - nor does a page whose
180
+ // canonical URL is another address (the sitemap lists canonical ones).
181
+ const canonical = data?.seo?.canonical ?? data?.canonical;
182
+ const pagePath = pageId === 'index' ? '/' : `/${pageId}/`;
183
+ if (!frontmatterNoindex(data) && !data?.url && !canonicalIsElsewhere(siteUrl, pagePath, canonical)) continue;
184
+ ids.add(pageId);
185
+ }
186
+ // Generated OpenAPI stub pages always set an explicit `slug` (see
187
+ // generate-api-pages.js) - there's no file-path-derived id to fall back
188
+ // to the way there is for a hand-written page.
189
+ const specsChanged = fileDates ? newestDate([...readSpecPaths(rootContentDir)].map((spec) => fileDates.get(spec))) : undefined;
190
+ for (const file of walkMdFiles(generatedDocsDir)) {
191
+ const { data } = matter(fs.readFileSync(file, 'utf-8'));
192
+ if (data?.slug && normalizeEntryId(data.slug) === 'index') rootIsPage = true;
193
+ if (data?.slug) pageIds.push(normalizeEntryId(data.slug));
194
+ // A generated API page changes when a spec does. Which spec it came
195
+ // from isn't recorded on the page, so it gets the newest of them.
196
+ if (data?.slug && specsChanged) lastModifiedById.set(normalizeEntryId(data.slug), specsChanged);
197
+ if (frontmatterNoindex(data) && data.slug) ids.add(normalizeEntryId(data.slug));
198
+ }
199
+ if (!rootIsPage) ids.add('index');
200
+ // Folder addresses with no page of their own redirect to one under them
201
+ // (lib/folder-redirects.js) - redirects, so not in the sitemap either.
202
+ for (const folder of folderAddresses(pageIds)) ids.add(folder);
203
+ return ids;
204
+ }
205
+
206
+ // Page id -> ISO date of its file's last commit; filled by
207
+ // collectNoindexIds(), which reads every page anyway.
208
+ const lastModifiedById = new Map();
209
+ const noindexIds = siteUrl ? collectNoindexIds(contentDir) : new Set();
210
+
211
+ /** O @astrojs/sitemap sempre grava um sitemap-index.xml apontando para
212
+ * sitemap-0.xml, sitemap-1.xml, ... - mesmo quando há um arquivo só, que é
213
+ * o caso de todo site de docs abaixo de 50.000 páginas. Aqui o único
214
+ * sitemap-0.xml vira sitemap.xml (o endereço que crawler e ferramenta de
215
+ * SEO procuram primeiro) e o índice é apagado. Com mais de um arquivo o
216
+ * índice é necessário (o protocolo não permite um único arquivo acima de
217
+ * 50.000 URLs), então tudo fica como o plugin gravou. Um sitemap.xml
218
+ * do próprio projeto (na raiz ou em public/ - já copiado para o build por
219
+ * publishProjectFiles() ou pelo Astro) também não é sobrescrito. */
220
+ function singleSitemapFile() {
221
+ return {
222
+ name: 'writedocs-single-sitemap',
223
+ hooks: {
224
+ 'astro:build:done': ({ dir }) => {
225
+ const outDir = fileURLToPath(dir);
226
+ const chunks = fs.readdirSync(outDir).filter((f) => /^sitemap-\d+\.xml$/.test(f));
227
+ const target = path.join(outDir, 'sitemap.xml');
228
+ if (chunks.length !== 1) {
229
+ report('debug', `${chunks.length} sitemap files generated - keeping sitemap-index.xml.`);
230
+ return;
231
+ }
232
+ if (fs.existsSync(target)) {
233
+ report('info', "The project has its own sitemap.xml, so it was kept - the generated sitemap is sitemap-index.xml.");
234
+ return;
235
+ }
236
+ fs.renameSync(path.join(outDir, chunks[0]), target);
237
+ fs.rmSync(path.join(outDir, 'sitemap-index.xml'), { force: true });
238
+ // O próprio plugin acabou de logar "sitemap-index.xml created"; esta
239
+ // linha diz o que de fato ficou no build.
240
+ report('debug', `Replaced ${chunks[0]} + sitemap-index.xml with a single sitemap.xml.`);
241
+ },
242
+ },
243
+ };
244
+ }
245
+
246
+ // writedocs.json's `redirects` array -> Astro's own `redirects` config option
247
+ // (a plain `{ [source]: destination }` record - see redirectSchema in
248
+ // lib/config.ts for why there's no `permanent`/status-code field: this
249
+ // package always builds `output: 'static'` with no adapter installed, and
250
+ // Astro's own docs say a static redirect is always a client-side
251
+ // `<meta http-equiv="refresh">` page regardless of what status is asked
252
+ // for). Omitted entirely (rather than passed as `{}`) when a site has no
253
+ // redirects configured, matching the `siteUrl ? [...] : []` pattern above
254
+ // of only opting into a feature's config surface when it's actually used.
255
+ // Generated API pages that moved to a new address (lib/moved-api-pages.js)
256
+ // redirect from the old one the same way; a redirect the site wrote itself
257
+ // for the same address comes later in the list, and wins.
258
+ const movedApiPages = readMovedApiPages(contentDir);
259
+ const redirectsConfig = Object.fromEntries([...movedApiPages, ...docsConfig.redirects].map((r) => [r.source, r.destination]));
260
+
261
+ /** Tailwind only scans the Vite root for class names - this package, not
262
+ * the site being built, which is usually somewhere else entirely - so a
263
+ * utility class written in a site's own MDX or snippet (Mintlify content
264
+ * uses them freely, e.g. className="block dark:hidden") never got
265
+ * generated. Appends an @source for the site's content files to
266
+ * global.css before Tailwind compiles it. Forward slashes, since
267
+ * Tailwind reads the path as a glob. */
268
+ function contentTailwindSource() {
269
+ const sourceGlob = `${contentDir.split(path.sep).join('/')}/**/*.{md,mdx,jsx,tsx}`;
270
+ return {
271
+ name: 'writedocs:content-tailwind-source',
272
+ enforce: 'pre',
273
+ transform(code, id) {
274
+ if (!id.split('?')[0].replace(/\\/g, '/').endsWith('/src/styles/global.css')) return null;
275
+ return { code: `${code}\n@source ${JSON.stringify(sourceGlob)};\n`, map: null };
276
+ },
277
+ };
278
+ }
279
+
280
+ export default defineConfig({
281
+ ...(siteUrl ? { site: siteUrl } : {}),
282
+ ...(Object.keys(redirectsConfig).length ? { redirects: redirectsConfig } : {}),
283
+ // Astro's own dev-mode toolbar (the floating pill in the bottom center
284
+ // of every page - inspect/audit/settings) is a tool for authoring
285
+ // Astro itself, not something a writedocs site's own reader/author
286
+ // should see while running `writedocs dev` - it's not exposed as a
287
+ // writedocs.json option (nothing site-specific to configure here) since
288
+ // there's no scenario where a writedocs project actually wants it on.
289
+ // Off in every environment (build never shows it anyway, since it's a
290
+ // dev-only overlay Astro strips from production output regardless).
291
+ devToolbar: { enabled: false },
292
+ // Not contentDir/dist directly - see writedocsBuildStagingDir()'s own
293
+ // comment (writedocs-temp-dir.js) for why, and build.js for the copy
294
+ // step that actually gets a finished build from here into the real
295
+ // <contentDir>/dist a reader/host ever sees. Irrelevant to `astro dev`
296
+ // (no build output involved), so this applies unconditionally rather
297
+ // than branching on which CLI command is running.
298
+ outDir: writedocsBuildStagingDir(packageRoot, contentDir),
299
+ cacheDir: path.join(writedocsTempDir(contentDir), 'cache'),
300
+ ...(fs.existsSync(contentPublicDir) ? { publicDir: contentPublicDir } : {}),
301
+ // icon() reads from whatever @iconify-json/* collections are installed
302
+ // (see package.json) and inlines only the specific icons a build
303
+ // actually references as <svg> - the installed collections don't
304
+ // affect output size beyond that. No `include` config needed: astro-icon
305
+ // resolves "collection:icon-name" against any installed collection
306
+ // automatically.
307
+ integrations: [
308
+ // markdown.processor (below) carries remarkAutoHydrateSnippets - see
309
+ // its own comment there for why it's attached there and not here.
310
+ // Auto-adds `client:load` to every usage of a component imported from
311
+ // a .jsx/.tsx file (a snippet - see docs/dev/docs/snippets.mdx) that
312
+ // doesn't already carry its own `client:*` attribute, so a snippet
313
+ // just works when dropped into a page - nobody using it needs to know
314
+ // Astro's hydration-directive syntax exists at all, only someone who
315
+ // wants a *different* strategy (client:visible/idle/only) needs to
316
+ // write one explicitly.
317
+ mdx(),
318
+ // Lets a site's own snippets (see docs/dev/docs/snippets.mdx) be real
319
+ // .jsx/.tsx React components - hooks and all - dropped straight into
320
+ // MDX and hydrated client-side as an Astro island (automatically -
321
+ // see remarkAutoHydrateSnippets above). writedocs' own built-in
322
+ // components (Callout, Card, ...) stay plain .astro files - this is
323
+ // purely for snippets a site author writes themselves.
324
+ react(),
325
+ icon(),
326
+ // A project's own files, published as they are (robots.txt, sitemap.xml,
327
+ // a PDF...) - before the sitemap integration, see
328
+ // lib/project-files-integration.js.
329
+ publishProjectFiles(contentDir),
330
+ ...(siteUrl
331
+ ? [
332
+ sitemap({
333
+ // Teto do protocolo de sitemap por arquivo (o default do
334
+ // @astrojs/sitemap é 45.000). Até aqui, tudo cabe num único
335
+ // sitemap.xml - ver singleSitemapFile() abaixo.
336
+ entryLimit: 50000,
337
+ filter: (page) => {
338
+ const pathname = new URL(page).pathname;
339
+ const id = normalizeEntryId(pathname);
340
+ return !noindexIds.has(id);
341
+ },
342
+ // <lastmod>, for the pages git has a date for.
343
+ serialize: (item) => {
344
+ const changed = lastModifiedById.get(normalizeEntryId(new URL(item.url).pathname));
345
+ return changed ? { ...item, lastmod: changed } : item;
346
+ },
347
+ }),
348
+ // Precisa vir depois do sitemap(): o Astro roda os hooks
349
+ // astro:build:done na ordem deste array, um de cada vez.
350
+ singleSitemapFile(),
351
+ ]
352
+ : []),
353
+ // After the sitemap: the generated robots.txt names the sitemap file.
354
+ generatedRobotsTxt({ siteUrl, seo: docsConfig.seo }),
355
+ // Lets styles.favicon/styles.logo/styles.background.images/seo.ogImage/
356
+ // styles.fonts.*.source resolve from anywhere in the project, not just
357
+ // public/ - see collectConfiguredAssetPaths() (lib/config.ts) for the
358
+ // field list and styles-asset-integration.js for how it's actually
359
+ // served/copied.
360
+ stylesAssetFallback(contentDir),
361
+ // /mcp in `writedocs dev`, as the build's dist/_worker.js serves it -
362
+ // see src/lib/mcp-dev-integration.js.
363
+ mcpDevServer({ version: JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf-8')).version }),
364
+ // writedocs dev: an edit to writedocs.json reloads the open tab.
365
+ configReload({ configPath: path.join(contentDir, 'writedocs.json') }),
366
+ ],
367
+ output: 'static',
368
+ // Dual Shiki themes for fenced code blocks (```) in MDX content, so
369
+ // they switch with the site's own [data-theme] toggle instead of
370
+ // always rendering Astro's single default (github-dark) regardless of
371
+ // light/dark mode. Defaults to github-light/github-dark, overridable
372
+ // per-site via writedocs.json's styles.codeblocks.{light,dark} (any Shiki
373
+ // theme *name* - see https://shiki.style/themes for the built-in
374
+ // list - not a custom theme object/JSON file, at least for now).
375
+ // Astro bakes the "light" theme's colors as the element's base inline
376
+ // style and adds --shiki-dark/--shiki-dark-bg (etc.) custom
377
+ // properties alongside it - see the
378
+ // [data-theme='dark'] :global(.astro-code) override in
379
+ // BaseLayout.astro that actually swaps to them.
380
+ markdown: {
381
+ // Excludes ```mermaid fences from Shiki's own tokenization entirely -
382
+ // they reach rehypeMermaid (below) as plain, un-highlighted text,
383
+ // which is what mermaid.js needs to parse and render them into an
384
+ // actual diagram client-side (see [...slug].astro's initMermaid()).
385
+ // Syntax-highlighting mermaid's own pseudo-language as if it were
386
+ // source code would be actively wrong here - the goal is a rendered
387
+ // diagram, not colored diagram-description text.
388
+ syntaxHighlight: { type: 'shiki', excludeLangs: ['mermaid'] },
389
+ // Astro 7's markdown.rehypePlugins (top-level) is deprecated in favor
390
+ // of passing plugins straight to the `unified` processor itself -
391
+ // functionally identical (Astro's own deprecated-option shim used to
392
+ // just forward the top-level array into this exact processor), just
393
+ // explicit instead of relying on that shim (and the console warning
394
+ // it prints on every build/dev run). Astro still runs this *after*
395
+ // its own internal Shiki step (see @astrojs/markdown-remark's
396
+ // index.js) regardless of which processor plugins are attached to,
397
+ // so rehypeMermaid still always sees the excluded ```mermaid block
398
+ // completely untouched by Shiki - exactly the plain
399
+ // <pre><code class="language-mermaid"> shape it expects to reshape
400
+ // into mermaid.js's <div class="mermaid"> form.
401
+ // remarkInjectBuiltinComponents/remarkAutoHydrateSnippets only ever
402
+ // match JSX/import nodes that exist solely in MDX's extended syntax
403
+ // tree (see mdx-inject-builtins.js/mdx-auto-hydrate.js) - running them
404
+ // here rather than passing them to mdx({ remarkPlugins }) avoids that
405
+ // option's own deprecation warning ("pass it to unified()... MDX will
406
+ // inherit it" - extendMarkdownConfig defaults to true, so mdx() below
407
+ // already picks this processor up automatically). Harmless no-op on
408
+ // plain .md content, which never has an mdxjsEsm/mdxJsxFlowElement
409
+ // node to match in the first place.
410
+ // remarkSubstituteVariables is a parameterized plugin (an "attacher"
411
+ // that takes writedocs.json's `variables` map as its options and returns
412
+ // the actual transformer) - passed as a unified [attacher, options]
413
+ // tuple, *not* pre-called (`remarkSubstituteVariables(docsConfig.variables)`
414
+ // directly in this array). unified's own `use()` always calls
415
+ // whatever it finds in this array as if it were the attacher itself;
416
+ // handing it an already-produced transformer function makes unified
417
+ // invoke *that* with zero arguments during its `freeze()` setup pass,
418
+ // which crashes deep inside unist-util-visit ("Cannot use 'in'
419
+ // operator to search for 'children' in undefined") the first time any
420
+ // MDX page actually builds - a real bug hit and fixed while testing
421
+ // 25-site-config, not a hypothetical. remarkInjectBuiltinComponents/
422
+ // remarkAutoHydrateSnippets don't need this tuple form since neither
423
+ // takes options - they're valid attachers as bare function references.
424
+ // A site with no `variables` set still gets this plugin instance
425
+ // (which then no-ops on every file - see its own early-return) rather
426
+ // than being conditionally omitted, keeping this array's shape static
427
+ // regardless of writedocs.json content.
428
+ processor: unified({
429
+ // remarkMath goes first: it parses $inline$ and standalone $$block$$
430
+ // math into their own `inlineMath`/`math` mdast node types (mdast-
431
+ // util-to-hast has built-in support for both, turning them into a
432
+ // <span>/<div> carrying the raw LaTeX source as a "language-math"
433
+ // code-like payload for rehypeKatex, below, to render). Running it
434
+ // before remarkSubstituteVariables means a $...$ span's raw LaTeX
435
+ // source is no longer a plain `text` node by the time that plugin's
436
+ // visitor runs (it only visits `text` nodes - see its own comment) -
437
+ // not that `[[key]]` syntax inside actual LaTeX is a realistic thing
438
+ // to write, but this keeps the two plugins' node-type boundaries
439
+ // clean rather than leaving it to chance which one sees a math span
440
+ // as raw text first.
441
+ remarkPlugins: [
442
+ remarkMath,
443
+ // Mintlify's Markdown-list <Tree> and <Prompt> source text - see
444
+ // lib/mdx-mintlify.js. Before remarkInjectBuiltinComponents, so
445
+ // the <Tree.Folder>/<Tree.File> elements they add are already in
446
+ // the tree when it looks for components to import.
447
+ remarkMintlifyTreeLists,
448
+ remarkMintlifyPromptText,
449
+ // An inline component that calls React hooks moves into a generated
450
+ // .jsx file so it runs as real React (and hydrates) - see
451
+ // lib/mdx-inline-react.js. Before remarkMintlifyReactHooks, which
452
+ // imports any hooks the page itself still calls (Mintlify
453
+ // pre-injects them), and before remarkAutoHydrateSnippets, which
454
+ // hydrates the component through its new .jsx import.
455
+ remarkExtractInlineReactComponents,
456
+ remarkMintlifyReactHooks,
457
+ // An unknown component becomes a fragment (its children still
458
+ // render) with a warning, instead of failing the whole build - see
459
+ // lib/mdx-unknown-components.js. After remarkMintlifyTreeLists, so
460
+ // the <Tree.Folder>/<Tree.File> elements it adds count as known.
461
+ remarkUnknownComponentFallback,
462
+ remarkInjectBuiltinComponents,
463
+ // Runs after remarkInjectBuiltinComponents (order doesn't actually
464
+ // matter between them - that plugin only ever prepends an import
465
+ // statement, never touches an existing JSX node's attributes) but
466
+ // grouped right next to it since both deal with the same set of
467
+ // built-in component tag names. See its own comment for why this
468
+ // has to be a whole-document pass rather than logic living inside
469
+ // Callout.astro/Accordion.astro themselves.
470
+ remarkTitleAnchorIds,
471
+ remarkAutoHydrateSnippets,
472
+ [remarkSubstituteVariables, docsConfig.variables],
473
+ ],
474
+ // rehypeKatex renders every math/inlineMath node remarkMath produced
475
+ // into real KaTeX markup (a <span class="katex">...</span> tree of
476
+ // MathML + HTML, not an image or client-rendered widget) - fully at
477
+ // build time, so unlike Mermaid there's no client-side JS or runtime
478
+ // cost at all, just the one katex.min.css import (BaseLayout.astro)
479
+ // for layout/glyph styling. Order relative to rehypeMermaid doesn't
480
+ // matter - they walk disjoint hast node shapes (pre>code.language-
481
+ // mermaid vs. remarkMath's own math/inlineMath-derived nodes) and
482
+ // neither plugin's output is visible to the other.
483
+ // rehypeImageLoading: lazy loading and sizes for content images - see
484
+ // lib/rehype-image-loading.js.
485
+ rehypePlugins: [rehypeMermaid, rehypeKatex, [rehypeImageLoading, { contentDir }]],
486
+ }),
487
+ shikiConfig: {
488
+ themes: codeblockTheme,
489
+ langAlias: codeblockLangAlias,
490
+ // The official @shikijs/transformers annotation transformers -
491
+ // enabled sitewide so any fenced code block can use their meta-
492
+ // string/comment syntax without per-page opt-in:
493
+ // ```js {1,3-5} -> transformerMetaHighlight
494
+ // ```js /someWord/ -> transformerMetaWordHighlight
495
+ // // [!code highlight] -> transformerNotationHighlight
496
+ // // [!code word:someWord] -> transformerNotationWordHighlight
497
+ // // [!code focus] -> transformerNotationFocus
498
+ // // [!code ++] / // [!code --] -> transformerNotationDiff
499
+ // // [!code error] / [!code warning] -> transformerNotationErrorLevel
500
+ // (comment syntax adapts to the language - # for Python/bash, //
501
+ // for JS/etc - see each transformer's own docs at shiki.style).
502
+ // Plus codeBlockTransformer, writedocs' own transformer for the
503
+ // copy button, an optional title bar, and wrap/lines/expandable
504
+ // meta flags - see src/lib/shiki-code-block.js. It runs last so
505
+ // its `root` hook wraps the <pre> only after every class the
506
+ // transformers above added to it is already in place - though in
507
+ // practice this doesn't matter, since all `pre`/`line` hooks
508
+ // across every transformer run to completion before any `root`
509
+ // hook runs at all (two separate passes, not interleaved).
510
+ transformers: [
511
+ transformerMetaHighlight(),
512
+ transformerMetaWordHighlight(),
513
+ transformerNotationHighlight(),
514
+ transformerNotationWordHighlight(),
515
+ transformerNotationFocus(),
516
+ transformerNotationDiff(),
517
+ transformerNotationErrorLevel(),
518
+ codeBlockTransformer(),
519
+ ],
520
+ },
521
+ },
522
+ // Tailwind is available for future/custom content (e.g. hand-authored
523
+ // MDX) but nothing in writedocs' own components has been migrated to
524
+ // it - they still use scoped <style> blocks + the --wd-* CSS variables
525
+ // so per-site writedocs.json theming (colors, and now dark mode) keeps
526
+ // working. See src/styles/global.css for the one @import that wires
527
+ // Tailwind's utilities in.
528
+ vite: {
529
+ // The dev server only serves files under its workspace root by default.
530
+ // A site's own snippets live in its content directory, and inline React
531
+ // components moved out of pages (lib/mdx-inline-react.js) in writedocs'
532
+ // temp directory - both need to reach the browser to hydrate. Setting
533
+ // `allow` replaces Vite's default rather than adding to it, so the
534
+ // package's dependencies must stay reachable too: when writedocs is
535
+ // installed, they sit next to it in the node_modules folder that
536
+ // contains it (React's own hydration client included), not inside
537
+ // packageRoot - see dependencyRoot above.
538
+ server: {
539
+ fs: {
540
+ allow: [packageRoot, dependencyRoot, contentDir, writedocsTempDir(contentDir)],
541
+ },
542
+ },
543
+ // contentTailwindSource() must come before tailwindcss(): both are
544
+ // enforce: 'pre' transforms, which Vite runs in array order, and
545
+ // Tailwind has to see the added @source when it compiles global.css.
546
+ // mintlifyReactHooksPlugin() does for a site's .jsx/.tsx snippets what
547
+ // remarkMintlifyReactHooks does for its MDX pages.
548
+ plugins: [contentTailwindSource(), tailwindcss(), mintlifyReactHooksPlugin(contentDir)],
549
+ // `writedocs dev`: Vite only prepares for the browser the dependencies
550
+ // it finds by scanning the project's own source - and when writedocs is
551
+ // installed, its source sits in node_modules, which the scan skips. The
552
+ // page script's `import("mermaid")` ([...slug].astro) was then served
553
+ // as it is, and its CommonJS dependencies failed in the browser ("dayjs
554
+ // ... does not provide an export named 'default'"): diagrams stayed as
555
+ // text in dev, while builds were fine. Naming it here prepares it always.
556
+ optimizeDeps: {
557
+ include: ['mermaid'],
558
+ },
559
+ resolve: {
560
+ alias: [
561
+ // Lets a page's MDX write `import Foo from '/snippets/foo.mdx'`
562
+ // (Mintlify's own snippet-import convention) instead of a
563
+ // relative path whose "../" depth depends on how deeply nested
564
+ // the importing page happens to be - see docs/dev/docs/snippets.mdx
565
+ // for the full feature writeup. Vite's project root is always
566
+ // packageRoot (this package itself - see run-astro.js), not
567
+ // contentDir, so a real leading-slash import would otherwise
568
+ // resolve (and fail to find anything) inside this package
569
+ // instead of the site's own content directory; this alias
570
+ // redirects just that one prefix to contentDir/snippets/ instead.
571
+ { find: /^\/snippets\//, replacement: path.join(contentDir, 'snippets') + '/' },
572
+ // remarkInjectBuiltinComponents (mdx-inject-builtins.js) auto-
573
+ // injects `import { Callout, ... } from 'writedocs/components'`
574
+ // into any .mdx file that uses a built-in component tag without
575
+ // importing it itself - a real bare specifier Vite has to resolve
576
+ // as if the .mdx file had written it. package.json's own
577
+ // `exports: { "./components": "./src/components/index.ts" }`
578
+ // makes that specifier valid *in principle* (Node's package
579
+ // self-reference feature - a package importing its own name), but
580
+ // self-reference only resolves when the importing file is a
581
+ // descendant of this package's own package.json - true for every
582
+ // existing fixture (always built from inside this repo/package
583
+ // tree) but never true for a real consumer's content, which lives
584
+ // in a completely separate directory in the actual product
585
+ // architecture (see docs/dev/docs/architecture.mdx) - walking up
586
+ // from such a file never finds a package.json named "writedocs",
587
+ // so self-reference fails and Vite reports the bare specifier as
588
+ // unresolvable ("Rolldown failed to resolve import
589
+ // 'writedocs/components'").
590
+ // This alias bypasses self-reference resolution entirely for
591
+ // that one specifier - Vite's alias matching is a plain string
592
+ // match against the specifier itself, independent of which file
593
+ // imported it, so it resolves correctly regardless of where the
594
+ // content directory actually lives. WRITEDOCS_PACKAGE_ROOT is the
595
+ // same packageRoot value already set by run-astro.js for
596
+ // lib/config.ts's fileIdForEntry() to consume - reusing it here
597
+ // instead of recomputing via import.meta.url keeps there being
598
+ // exactly one source of truth for "where this package lives" per
599
+ // astro subprocess. Falls back to this file's own directory
600
+ // (astro.config.mjs always lives at packageRoot) for anything
601
+ // that ever imports this config outside that subprocess, e.g. a
602
+ // future test harness.
603
+ {
604
+ find: 'writedocs/components',
605
+ replacement: path.join(packageRoot, 'src/components/index.ts'),
606
+ },
607
+ ],
608
+ },
609
+ },
610
+ });